const jwt = require("jsonwebtoken");
const pool = require("../pool.js");
const { v4: uuidv4 } = require('uuid');
const fs = require('fs');
const path = require('path');
const {errLog}=require("../utils/err");//日志记录
const request = require('request')
const crypto = require('crypto');
const {systemSettings} =require("../utils/menuString");
const CHANGE_DATE = '2024-06-06'; 
var md5=require("md5") 



const NodeCache = require("node-cache");
const myCache = new NodeCache({ stdTTL: 600 }); // 验证码有效期10分钟


module.exports = {
    // 存储手机验证码
    storePhoneVerificationCode(phoneNumber, code) {
        myCache.set(phoneNumber, code);
    },
   
  // 检索手机验证码
    retrievePhoneVerificationCode(phoneNumber) {
        return myCache.get(phoneNumber);
    },
   
  // 删除手机验证码
    deletePhoneVerificationCode(phoneNumber) {
        myCache.del(phoneNumber);
    },
    setToken({uid}) {
        let token = jwt.sign({uid}, "user", {
            expiresIn: "86400s", // 授权时间
        });
        return token;
    },
    verToken(token) {
        try {
            let res = jwt.verify(token, "user");
            return res;
        } catch (err) {
            return false;
        }
    },
    /**
     * 判断名称是否重复
     * @param string sql sql语句
     * @param string name sql查询参数name
     * @param string msg 提示语
     * @param object req 请求主体
     * @param object res 响应主体
     * */
    existName({sql, name,msg="名称已存在！",req,res}) {
        return new Promise((resolve, reject) => {
            if(!name) return resolve(true);
            pool.query(sql, [name], (err, result) => {
                if (err) return res.send(this.returnData({code:-1,msg,err,req}))
                if (result.length > 0) return res.send(this.returnData({code:-1,msg,err,req}))
                resolve(true);
            })
        })
    },
    /**
     * 判断修改的名称是否和修改前的一样
     * @param string sql sql语句
     * @param string sqlName 修改前的属性名
     * @param string name 修改后的值
     * @param number id sql条件参数
     * */
    judgeUserName({sql,sqlName="name", name,id}) {
        return new Promise((resolve, reject) => {
            // let sql = "SELECT name FROM user WHERE  id=?";
            pool.query(sql, [id], (err, result) => {
                if (err) return resolve(1);
                if (result[0][sqlName] == name) return resolve(-1);
                return resolve(1);
            })
        })
    },
    /**
     * 响应总函数
     * @param number code 状态码
     * @param string msg 提示文字
     * @param number total 查询总数量
     * @param object data 数据
     * @param object err 错误信息
     * @param object req 错误信息
     * @param object funName 错误信息记录名称
     * */
    returnData({code = 1, msg, total=0,data = {},err,req={},funName} = {}) {
        if (code == 1 && !msg) msg = "请求成功！";
        if (code == -1 && !msg) msg = "服务器异常！";
        if (code == 203 && !msg) msg = "登陆失效，请重新登陆！";
        let res={code, msg, data};
        if(total!==0) res.total=total;
        if(err) res.err=err;
        //记录错误日志
        if(code!=1) errLog({err,code,msg,req,funName});
        return res;
    },
    /**
     * 获取用户信息
     * @param object req 请求主体
     * @param object res 响应主体
     * */
    getUserInfo(req, res) {
        return new Promise(resolve => {
            let token = req.headers.token;
            if (!token) return res.send(this.returnData({code: 203,req}));
            let user = this.verToken(token);
            if (!user) return res.send(this.returnData({code: 203,req}));
            console.log(132432,user);
            let sql = "SELECT id,name,status,roles_id AS rolesId,admin,more_id AS moreId FROM user WHERE id=?";
            pool.query(sql, [user.uid], (err, result) => {
                if (err) return res.send(this.returnData({code: -1, msg: "服务端用户信息获取错误！",err,req}));
                if (result.length === 0) return res.send(this.returnData({code: -1, msg: "用户不存在！",err,req}));
                resolve(result[0]);
            })
        })
    },
    /**
     * 分页页码处理
     * @param number page 页码
     * @param number size 最大数量
     * */
    pageSize(page,size){
        if(!page){page=1};
        if(!size){size=9999999};
        page = (page-1)*size;
        size = parseInt(size);
        return {page,size}
    },
    /**
     * 查询总数
     * @param string name 表名
     * @param string where 查询条件
     * @param object res 主体
    * */
    getSum({name,where,res,req}) {
        return new Promise((resolve, reject) => {
            let sql = `SELECT count(1) FROM ${name} ${where}`;
            pool.query(sql, (err, result) => {
                if (err) return res.send(this.returnData({code: -1, msg: "获取数据总数错误！",err,req}));
                resolve({ total: result[0]["count(1)"] });
            });
        })
    },
    getSumBySql({sql,res,req}) {
        return new Promise((resolve, reject) => {
            pool.query(sql, (err, result) => {
                if (err) return res.send(this.returnData({code: -1, msg: "获取数据总数错误！",err,req}));
                resolve({ total: result[0]["count(1)"] });
            });
        })
    },
    getSumByCorn({name,where}) {
        return new Promise((resolve, reject) => {
            let sql = `SELECT count(1) FROM ${name} ${where}`;
            pool.query(sql, (err, result) => {
                resolve({ total: result[0]["count(1)"] });
            });
        })
    },
    /**
     * 获取用户权限
     * @param object req 请求主体
     * @param object res 响应主体
     * */
    getUserRole(req, res) {
        
        return new Promise(async (resolve, reject) => {
            let user = await this.getUserInfo(req, res);
            let userSql = "SELECT roles,role_key FROM roles WHERE FIND_IN_SET(id,?)";
            pool.query(userSql, [user.rolesId], (err, result) => {
                if (err || result.length == 0) return res.send(this.returnData({code:-1,msg:"获取权限失败！",err,req}))
                let roles = result.map(t => t.roles);
                //权限字符
                let roleKey=result.map(t=>t.role_key);
                //角色权限
                let roleAdmin=roleKey.some(t=>t==="admin");
                resolve({userRole: roles.join(","),roleKey,user,roleAdmin});
            });
        });
    },
    /**
     * 菜单字符权限拦截
     * @param object req 主体
     * @param object res 主体
     * @param array role 接口权限字符数组
     * @param boolean admin 是否管理员也要遵守（默认否）
     * */
    checkPermi({req,res,role=[],admin=false}){
        return new Promise(async (resolve, reject)=>{
            let userRole=await this.getUserRole(req,res);
            if((userRole.roleAdmin|| userRole.user.admin===1)&&!admin) return resolve(true);
            let sql = "SELECT role_key AS roleKey FROM router_menu WHERE FIND_IN_SET(id,?)";
            pool.query(sql,[userRole.userRole],(err,result)=>{
                try {
                    if(err) return res.send(this.returnData({code:-1,msg:"菜单权限判断错误！",err,req}))
                    let roleKeyArr=result.map(t=>t.roleKey).filter(t=>t);
                    const hasPermission = role.some(permission => {
                        return roleKeyArr.includes(permission)
                    });
                    if(hasPermission) return resolve(hasPermission);
                    res.send(this.returnData({code:-1,msg:"暂无对应菜单请求权限！",err,req}))
                }catch (e) {
                    res.send(this.returnData({code:-1,msg:"菜单权限判断错误！！",err:e,req}))
                }
            })
        })
    },
    /**
     * 角色权限拦截
     * @param object req 主体
     * @param object res 主体
     * @param array role 角色权限数组
     * @param boolean admin 是否管理员也要遵守（默认否）
     * */
    async checkRole({req,res,role=[],admin=false}){
        try {
            let userRole=await this.getUserRole(req,res);
            if((userRole.roleAdmin|| userRole.user.admin===1)&&!admin) return true;
            let roleKeyArr=userRole.roleKey;
            const hasPermission = role.some(permission => {
                return roleKeyArr.includes(permission)
            });
            if(hasPermission) return true;
            res.send(this.returnData({code:-1,msg:"暂无对应角色请求权限！",req}))
            return Promise.reject(false);
        }catch (e) {
            res.send(this.returnData({code:-1,msg:"角色权限判断错误！",err:e,req}))
            return Promise.reject(false);
        }

    },
    /**
     * 是否操作的是用户总管理员
     * @param object req 请求主体
     * @param object res 响应主体
     * @param number id 查询条件id
     * */
    upAdmin({req,res,id}){
        return new Promise((resolve, reject)=>{
            let sql = "SELECT admin FROM user WHERE id=?";
            pool.query(sql,[id],(err,result)=>{
                if(err||result.length===0) return res.send(this.returnData({code:-1,msg:"管理信息判断错误！",err,req}));
                if(result[0].admin===1) return res.send(this.returnData({code:-1,msg:"无法对《总管理》执行此操作！",err,req}));
                resolve(result);
            })
        })

    },
    /**
     * 是否操作的是角色总管理员
     * @param object req 请求主体
     * @param object res 响应主体
     * @param number id 查询条件id
     * */
    upAdminRole({req,res,id}){
        return new Promise((resolve, reject)=>{
            let sql = "SELECT role_key FROM roles WHERE id=?";
            pool.query(sql,[id],(err,result)=>{
                if(err||result.length===0) return res.send(this.returnData({code:-1,msg:"管理信息判断错误！！",err,req}));
                if(result[0].role_key==="admin") return res.send(this.returnData({code:-1,msg:"无法对《角色总管理》执行此操作！",err,req}));
                resolve(result);
            })
        })

    },
    /**
     * 通过id获取用户信息
     * @param object req 请求主体
     * @param object res 响应主体
     * @param number id 查询条件id
     * */
    getUserId({req,res,id}){
        return new Promise((resolve, reject)=>{
            let sql = "SELECT admin FROM user WHERE id=?";
            pool.query(sql,[id],(err,result)=>{
                if(err||result.length===0) return res.send(this.returnData({code:-1,msg:"用户信息错误！！",err,req}));
                resolve(result[0]);
            })
        })

    },
    // 递归计算目录下文件的数量
    countStaticAssets(dir) {
        fs.readdir(dir, (err, files) => {
            if (err) {
                return 0;
            }
            let count = 0;
            let pending = files.length;
            if (pending === 0) {
                // 如果没有文件，则直接调用回调函数
                return 0;
            }
            files.forEach((file) => {
                fs.stat(path.join(dir, file), (err, stats) => {
                    if (err) {
                        return 0;
                    }
                    if (stats.isFile()) {
                        count++;
                    }
                    if (--pending === 0) {
                        return count;
                    }
                });
            });
        });
    },
    getDataString(){
        const now = new Date();
        const year = now.getFullYear();
        const month = ('0' + (now.getMonth() + 1)).slice(-2);
        const day = ('0' + now.getDate()).slice(-2);
        const hours = ('0' + now.getHours()).slice(-2);
        const minutes = ('0' + now.getMinutes()).slice(-2);
        const seconds = ('0' + now.getSeconds()).slice(-2);
        return year + month + day + hours + minutes + seconds;

    },
    getOrderNo(fmt){
        let date=new Date();
			  var o = {
			    "M+" : date.getMonth()+1,                 //月份
			    "d+" : date.getDate(),                    //日
			    "h+" : date.getHours(),                   //小时
			    "m+" : date.getMinutes(),                 //分
			    "s+" : date.getSeconds(),                 //秒
			    "q+" : Math.floor((date.getMonth()+3)/3), //季度
			    "S"  : date.getMilliseconds()             //毫秒
			  };
			
			  if(/(y+)/.test(fmt)){
			    fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
			  }
			        
			  for(var k in o){
			    if(new RegExp("("+ k +")").test(fmt)){
			      fmt = fmt.replace(
			        RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));  
			    }       
			  }
			
			  return fmt;        
    },
    /**
 * 解密
 *
 * @param {string} cipherText 文本
 * @param {string} key 平台密钥
 * @param {string} iv 偏移量（nonce）
 * @param {string} add associated_data
 */
     decodeByAES: (cipherText, key, iv, add) => {
        let rst = '';
        cipherText = Buffer.from(cipherText, 'base64');
        let authTag = cipherText.slice(cipherText.length - 16);
        let data = cipherText.slice(0, cipherText.length - 16);
        let decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
        decipher.setAuthTag(authTag);
        decipher.setAAD(Buffer.from(add));
        rst = decipher.update(data, 'binary', 'utf8');
        try {
          rst += decipher.final('utf-8');
        } catch (e) {
          think.logger.error(e.toString());
        }
        return rst;
      },
       /**
     * 获取会员Id
     * @param object req 请求主体
     * @param object res 响应主体
     * */
    getTUserId({phone,req, res}) {
        console.log(1,phone);
        return new Promise(resolve => {
            let sql = "SELECT * FROM t_user WHERE phone=?";
            console.log(2);
            pool.query(sql, [phone], (err, result) => {
                console.log(3,result);
                if (err) return res.send(this.returnData({code: -1, msg: "服务端用户信息获取错误！",err,req}));
                if (result.length === 0){
                    console.log(4);
                    const UUID = uuidv4();
                    let sql = "INSERT INTO t_user(source, phone, uid, open_id, created_at, updated_at) VALUES (?,?,?,?,?,?)";
                    pool.query(sql, ["来伊份",phone,UUID,"",new Date(),new Date()], (err2, result2) => {
                        if (err) return res.send(utils.returnData({code: -1,err}));
                        console.log(120000,result2.insertId);
                        resolve(UUID);
                    });
                }else{
                    console.log(55555,result[0]);
                    console.log(55555,result[0].uid);
                    resolve(result[0].uid);
                }
                
            })
        })
    },
    getTUserIdByCorn({phone}) {
        console.log(1,phone);
        return new Promise(resolve => {
            let sql = "SELECT * FROM t_user WHERE phone=?";
            console.log(2);
            pool.query(sql, [phone], (err, result) => {
                console.log(3,result);
                if (result.length === 0){
                    console.log(4);
                    const UUID = uuidv4();
                    let sql = "INSERT INTO t_user(source, phone, uid, open_id, created_at, updated_at) VALUES (?,?,?,?,?,?)";
                    pool.query(sql, ["来伊份",phone,UUID,"",new Date(),new Date()], (err2, result2) => {
                        console.log(120000,result2.insertId);
                        resolve(UUID);
                    });
                }else{
                    console.log(55555,result[0]);
                    console.log(55555,result[0].uid);
                    resolve(result[0].uid);
                }
                
            })
        })
    },
       /**
     * 获取产品Id
     * @param object req 请求主体
     * @param object res 响应主体
     * */
        getProductId({skuId,skuCode,skuName,req, res}) {
            return new Promise(resolve => {
                let sql = "SELECT * FROM product WHERE sku_id=? and sku_code=? and sku_name=?";
                pool.query(sql, [skuId,skuCode,skuName], (err, result) => {
                    if (err) return res.send(this.returnData({code: -1, msg: "服务端产品信息获取错误！",err,req}));
                    // if (result.length === 0) return res.send(this.returnData({code: -1, msg: "找不到产品！",err,req}));
                    if (result.length === 0) resolve(0);
                    resolve(result[0].id);
                })
            })
        },
        getProductIdByCorn({skuId,skuCode,skuName}) {
            return new Promise(resolve => {
                let sql = "SELECT * FROM product WHERE sku_id=? and sku_code=? and sku_name=?";
                pool.query(sql, [skuId,skuCode,skuName], (err, result) => {
                    if (result.length === 0) resolve(0);
                    resolve(result[0].id);
                })
            })
        },
        getConsigneeId({province,city,phone,county,address,name,req, res}) {
            return new Promise(resolve => {
                let sql = "SELECT id FROM t_user_consignee WHERE province=? and city=? and phone=? and county=? and detail_address=? and name=?";
                pool.query(sql, [province,city,phone,county,address,name], (err, result) => {
                    if (err) return res.send(this.returnData({code: -1, msg: "服务端地址信息获取错误！",err,req}));
                    // if (result.length === 0) return res.send(this.returnData({code: -1, msg: "找不到产品！",err,req}));
                    if (result.length === 0) resolve(0);
                    resolve(result[0].id);
                })
            })
        },
        getConsigneeIdByCorn({province,city,recipientNumber,county,address,name}) {
            console.log(province,city,recipientNumber,county,address,name);
            return new Promise(resolve => {
                let sql = "SELECT id FROM t_user_consignee WHERE province=? and city=? and phone=? and county=? and detail_address=? and name=?";
                pool.query(sql, [province,city,recipientNumber,county,address,name], (err, result) => {
                    console.log('12354');
                    console.log(result);
                    console.log('12354');
                    if (result.length === 0) resolve(0);
                    resolve(result[0].id);
                })
            })
        },
        sedMessage(phone,skuName){
            return new Promise(resolve => {
                var http = require('http');  
                var sha1=require('sha1');
                var qs = require('querystring'); 
                var Appkey='13a4c1d079b489504c896be4c0abe0da';
                var Nonce="asd";
                var CurTime=2221222;
                var AppSecret='d5abccde1e8f';
                var str=AppSecret + Nonce + CurTime;
                var CheckSum=sha1(str);
                    
                var post_data = {  
                    templateid:22534438,
                    mobiles:`['`+phone+`']`,
                    params:`['`+skuName+`']`,
                };
                    
                var content = qs.stringify(post_data); //序列化 a=c&name=d  并且将中文字符进行urlencode 编码进行传输
                    console.log(content)
                var options = {  
                    hostname: 'api.netease.im',  
                    //port:443,
                    path: '/sms/sendtemplate.action?'+content,  
                    method: 'POST',  
                    headers: {  
                    'AppKey'		: Appkey,
                    'Nonce'			: Nonce,
                    'CurTime'		: CurTime,
                    'CheckSum'		: CheckSum,
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                        
                    }  
                };  
                var req = http.request(options, function (result) {  
                    console.log('STATUS: ' + result.statusCode);  
                    result.setEncoding('utf8');  
                    result.on('data', function (chunk) {  
                        console.log('BODY: ' + chunk); 
                        let data=JSON.parse(chunk)
                        console.log(666,data.code);
                        if(data.code==200){
                            console.log('推送短信发送成功');
                            resolve({code:data.code,msg:data.obj});
                        }else{
                            console.log('推送短信发送失败');
                            resolve({code:data.code,msg:data.obj});
                        }
                    });  
                });  
                    
                req.on('error', function (e) {  
                    console.log('problem with request: ' + e.message);  
                });  
                req.end();
            })
        },
        //HTTP短信对接
        sedHttpMessage(phone,skuName){
            let messages="【来伊份】您的"+skuName+"权益已下发，打开“来伊份零食会员权益”微信小程序领取；（在微信顶部搜索框输入“来伊份零食会员权益”搜索小程序）客服4008819777拒收请回复R";
            const timestamp = Date.now();
            const userName ="200143";
            const password ="yLV4bF4B13g1";
            return new Promise(resolve => {
                var http = require('http');  
                const data = JSON.stringify({
                    userName:userName,
                    messageList:[{
                        phone:phone,
                        content:messages
                    }],
                    timestamp:timestamp,
                    sign:md5(userName + timestamp + md5(password)),
                });
                var options = {  
                    hostname: '47.92.88.197',  
                    port:8001,
                    path: '/sms/api/sendMessageOne',  
                    method: 'POST',  
                    headers: {  
                        'Content-Type': 'application/json;charset=utf-8',
                    }  
                };  
                var req = http.request(options, function (result) {  
                    console.log('STATUS: ' + result.statusCode);  
                    result.setEncoding('utf8');  
                    result.on('data', function (chunk) {  
                        console.log('BODY: ' + chunk); 
                        let jsonData=JSON.parse(chunk)
                        console.log(666,jsonData.data);
                        if(jsonData.data[0].code==0){
                            console.log('推送短信发送成功');
                            resolve({code:jsonData.data[0].code,msg:jsonData.data[0].message,msgId:jsonData.data[0].msgId});
                        }else{
                            console.log('推送短信发送失败');
                            resolve({code:jsonData.data[0].code,msg:jsonData.data[0].message});
                        }
                    });  
                });  
                    
                req.on('error', function (e) {  
                    console.log('problem with request: ' + e.message);  
                });  
                req.write(data);
                req.end();
            })
        },
        //春节期间短信
        sedHttpSpringMessage(phone){
            const currentDate = new Date();
            const specifiedDate = new Date("2025-02-07");
            const result = currentDate > specifiedDate;
            console.log(123,result);
            if(result){
                return null;
            }else{
                let messages="【来伊份】尊敬的用户：因春节物流运力紧张，会影响权益到达率及保质期；1月22号-2月7日订单，会在2月8日后按购买顺序发货。询19705053135";
                const timestamp = Date.now();
                const userName ="200143";
                const password ="yLV4bF4B13g1";
                return new Promise(resolve => {
                    var http = require('http');  
                    const data = JSON.stringify({
                        userName:userName,
                        messageList:[{
                            phone:phone,
                            content:messages
                        }],
                        timestamp:timestamp,
                        sign:md5(userName + timestamp + md5(password)),
                    });
                    var options = {  
                        hostname: '47.92.88.197',  
                        port:8001,
                        path: '/sms/api/sendMessageOne',  
                        method: 'POST',  
                        headers: {  
                            'Content-Type': 'application/json;charset=utf-8',
                        }  
                    };  
                    var req = http.request(options, function (result) {  
                        console.log('STATUS: ' + result.statusCode);  
                        result.setEncoding('utf8');  
                        result.on('data', function (chunk) {  
                            console.log('BODY: ' + chunk); 
                            let jsonData=JSON.parse(chunk)
                            console.log(666,jsonData.data);
                            if(jsonData.data[0].code==0){
                                console.log('推送短信发送成功');
                                resolve({code:jsonData.data[0].code,msg:jsonData.data[0].message,msgId:jsonData.data[0].msgId});
                            }else{
                                console.log('推送短信发送失败');
                                resolve({code:jsonData.data[0].code,msg:jsonData.data[0].message});
                            }
                        });  
                    });  
                        
                    req.on('error', function (e) {  
                        console.log('problem with request: ' + e.message);  
                    });  
                    req.write(data);
                    req.end();
                })
            }
        },
        //发送登录短信
        sedLoginMessage(phone,code){
            let messages="【来伊份】来伊份零食会员权益平台登录验证码："+code+"（10分钟内有效）";
            const timestamp = Date.now();
            const userName ="200143";
            const password ="yLV4bF4B13g1";
            return new Promise(resolve => {
                var http = require('http');  
                const data = JSON.stringify({
                    userName:userName,
                    messageList:[{
                        phone:phone,
                        content:messages
                    }],
                    timestamp:timestamp,
                    sign:md5(userName + timestamp + md5(password)),
                });
                var options = {  
                    hostname: '47.92.88.197',  
                    port:8001,
                    path: '/sms/api/sendMessageOne',  
                    method: 'POST',  
                    headers: {  
                        'Content-Type': 'application/json;charset=utf-8',
                    }  
                };  
                var req = http.request(options, function (result) {  
                    console.log('STATUS: ' + result.statusCode);  
                    result.setEncoding('utf8');  
                    result.on('data', function (chunk) {  
                        console.log('BODY: ' + chunk); 
                        let jsonData=JSON.parse(chunk)
                        console.log(666,jsonData.data);
                        if(jsonData.data[0].code==0){
                            console.log('登录短信发送成功');
                            resolve({code:jsonData.data[0].code,msg:jsonData.data[0].message,msgId:jsonData.data[0].msgId});
                        }else{
                            console.log('登录短信发送失败');
                            resolve({code:jsonData.data[0].code,msg:jsonData.data[0].message});
                        }
                    });  
                });  
                    
                req.on('error', function (e) {  
                    console.log('problem with request: ' + e.message);  
                });  
                req.write(data);
                req.end();
            })
        },


        //获取当前日期时间
        getDateTime() {
            const today = new Date();
            const year = today.getFullYear();
            const month = today.getMonth() + 1; // 月份是从0开始的
            const day = today.getDate();
            const hours = today.getHours();
            const minutes = today.getMinutes();
            const seconds = today.getSeconds();
             
            // 格式化月份和日期，确保它们至少有两位数字
            const formattedMonth = month.toString().padStart(2, '0');
            const formattedDay = day.toString().padStart(2, '0');
            const formattedHours = hours.toString().padStart(2, '0');
            const formattedMinutes = minutes.toString().padStart(2, '0');
            const formattedSeconds = seconds.toString().padStart(2, '0');
             
            // 组合成一个字符串
            const todayDate = `${year}-${formattedMonth}-${formattedDay} ${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
            return todayDate;
        },
        //获取当前日期时间
        getDateTimeNoSen() {
            const today = new Date();
            const year = today.getFullYear();
            const month = today.getMonth() + 1; // 月份是从0开始的
            const day = today.getDate();
            const hours = today.getHours();
            const minutes = today.getMinutes();
            const seconds = today.getSeconds();
             
            // 格式化月份和日期，确保它们至少有两位数字
            const formattedMonth = month.toString().padStart(2, '0');
            const formattedDay = day.toString().padStart(2, '0');
            const formattedHours = hours.toString().padStart(2, '0');
            const formattedMinutes = minutes.toString().padStart(2, '0');
            const formattedSeconds = seconds.toString().padStart(2, '0');
             
            // 组合成一个字符串
            const todayDate = `${year}-${formattedMonth}-${formattedDay} ${formattedHours}:${formattedMinutes}`;
            return todayDate;
        },
        getDate() {
            const today = new Date();
            const year = today.getFullYear();
            const month = today.getMonth() + 1; // getMonth() 返回的月份是从 0 开始的
            const day = today.getDate();
            const todayDate=`${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
            return todayDate;
        },
        getDateBefore() {
            const today = new Date();
            const year = today.getFullYear();
            const month = today.getMonth() + 1; // getMonth() 返回的月份是从 0 开始的
            const day = today.getDate()-1;
            const todayDate=`${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
            return todayDate;
        },
        getDaysAgo(days) {
            const date = new Date();
            date.setDate(date.getDate() - days);
            return date.toISOString().split('T')[0];
        },

        
        //查询第三方订单
        getLaiyifenOrder(startTime,page) {
            return new Promise(resolve => {
                const currentDate = new Date();
                const year = currentDate.getFullYear().toString();
                const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
                const day = (currentDate.getDate()+ 1).toString().padStart(2, '0');
                const dateString = `${year}-${month}-${day}`;
                let endTime=dateString;
                console.log("拉订单的开始时间："+startTime);
                console.log("拉订单的结束时间："+endTime);
                request.post('https://lyf.9tax.com/transfer-server/open/orderList', {
                    json: {
                    pageNo:page,
                    pageSize:50,
                    startTime:startTime,
                    endTime:endTime
                    }
                }, (error, result, body) => {
                    if (error) {
                        console.error(error)
                        return
                    }
                    if(result.statusCode==200){
                        let dataJson=body.data;
                        // console.log(dataJson.length)
                        // console.log(dataJson)
                        resolve(dataJson);
                    }
                })
            })
        },
         //查询第三方订单
         getLaiyifenOrderTen(startTime,page) {
            return new Promise(resolve => {
                console.log("拉订单的开始时间："+startTime);
                console.log("拉订单的结束时间："+CHANGE_DATE);
                request.post('https://lyf.9tax.com/transfer-server/open/orderList', {
                    json: {
                    pageNo:page,
                    pageSize:50,
                    startTime:startTime,
                    endTime: CHANGE_DATE
                    }
                }, (error, result, body) => {
                    if (error) {
                        console.error(error)
                        return
                    }
                    if(result.statusCode==200){
                        let dataJson=body.data;
                        // console.log(dataJson.length)
                        // console.log(dataJson)
                        resolve(dataJson);
                    }
                })
            })
        },
        //匹配地址
        extractAddressComponents(address) {
            const provinceRegex = /(?<province>[^省]+省|[^自治区]+自治区|[^市]+市)/;
            const cityRegex = /(?<city>[^市]+市|[^县]+县)/;
            const districtRegex = /(?<district>[^区]+区|[^县]+县|[^乡]+乡|[^镇]+镇|[^街]+街)/;
            const detailsRegex = /(?<details>[^]+)/;
           
            let match;
            match = address.match(provinceRegex);
            const province = (match && match.groups.province) || '';
           
            match = address.substring(province.length).match(cityRegex);
            const city = (match && match.groups.city) || '';
           
            match = address.substring(province.length + city.length).match(districtRegex);
            const district = (match && match.groups.district) || '';
           
            const details = address.substring(province.length + city.length + district.length).match(detailsRegex);
           
            return {
              province: province.trim(),
              city: city.trim(),
              district: district.trim(),
              details: (details && details.groups.details) || ''
            };
          },
          //推送小程序消息订阅
            async startToast(openid,express_company,trackingNumber,skuName) {
                console.log(123,this.getDateTimeNoSen())
                const ART_APP_ID = systemSettings.wxpay.APPID//AppID(小程序ID)
                const ART_APP_SECRET =systemSettings.wxpay.ART_APP_SECRET //AppSecret(小程序密钥)	
                // 小程序的access_token获取地址，需要替换你的appId和appSecret
                const accessTokenUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${ART_APP_ID}&secret=${ART_APP_SECRET}`;
                
                // 获取access_token
                request({url: accessTokenUrl, json: true}, (error, response, body) => {
                if (!error && response.statusCode === 200) {
                    const accessToken = body.access_token;
                
                    // 订阅消息推送地址，需要替换你的toUser和templateId
                    const subscribeMessageUrl = `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${accessToken}`;
                
                    const message = {
                    "touser": openid,
                    "template_id": "9cfuuyH99tleq365J0uTFoOEdHOk-Kldi-kZoKzr7mI",
                    "page": "pages/index/index",
                    "data": {
                        "date4": { "value": this.getDateTime() },
                        "thing1": { "value": express_company },
                        "character_string5": { "value": trackingNumber },
                        "thing11": { "value": skuName }
                    },
                    // "miniprogram_state":"trial",
                    // "miniprogram_state":"formal",
                    // "lang":"zh_CN"
                    };
                    console.log(8990,message);
                    console.log(8990,accessToken);
                    // 发送订阅消息
                    request.post({url: subscribeMessageUrl, body: message, json: true}, (error, response, body) => {
                        if (!error && response.statusCode === 200) {
                            console.log('消息推送成功', body);
                        } else {
                            console.error('消息推送失败', error || body);
                        }
                    });
                } else {
                    console.error('获取access_token失败', error || body);
                }
                });
            },
};
